package com.ufo.store.management.ui.activity;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.annotation.Size;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import com.ufo.store.management.R;
import com.ufo.store.management.utils.StatusBarUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by taoli on 2016/6/23.
 */
public class BaseActivity extends AppCompatActivity {
    public static final String TAG = "BaseActivity";

    /**
     * 默认请求码
     */
    public int mPermissionRequestCode = 10001;
    /**
     * 权限请求监听接口
     */
    private PermissionListener listener;

    @SuppressLint("InlinedApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //沉浸式主题
        setLightBar(R.color.app_bar_color);
    }

    protected void setLightBar(int color){
        //状态栏设置标题颜色
        //StatusBarUtil.setStatusBarColor(this,R.color.a1_orange_color,false);
        //状态栏白色主题
        StatusBarUtil.StatusBarLightMode(this,color,false);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public Activity getActivity(){
        return this;
    }

    public void setListener(PermissionListener listener) {
        this.listener = listener;
    }

    /**
     * 检测是否有所需权限
     *
     * @param context
     * @param perms   所需权限数组
     * @return
     */
    public static boolean checkPermissions(@NonNull Context context,
                                           @Size(min = 1) @NonNull String... perms) {
        // Always return true for SDK < M, let the system deal with the permissions
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            Log.i(TAG,"hasPermissions: API version < M, returning true by default");

            // DANGER ZONE!!! Changing this will break the library.
            return true;
        }

        // Null context may be passed if we have detected Low API (less than M) so getting
        // to this point with a null context should not be possible.
        if (context == null) {
            throw new IllegalArgumentException("Can't check permissions for null context");
        }

        for (String perm : perms) {
            if (ContextCompat.checkSelfPermission(context, perm)
                    != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }

        return true;
    }

    /**
     * 申请权限
     *
     * @param requestCode 请求码
     * @param permissions 需要申请的权限
     */
    @TargetApi(Build.VERSION_CODES.M)
    public void requestPermissions(int requestCode, @NonNull String[] permissions) {
        mPermissionRequestCode = requestCode;
        List<String> requestPermissionList = new ArrayList<>();
        //查找未获取的权限
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                requestPermissionList.add(permission);
            }
        }
        if (requestPermissionList.isEmpty()) {
            //已获取所有请求权限
            permissionAllGranted(mPermissionRequestCode);
        } else {
            //获取权限
            requestPermissions(requestPermissionList.toArray(
                    new String[requestPermissionList.size()]), mPermissionRequestCode);
        }
    }

    /**
     * 申请权限结果
     *
     * @param requestCode  请求码 要等于申请时候的请求码
     * @param permissions  申请的权限数组
     * @param grantResults 对应权限的处理结果
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode != mPermissionRequestCode) {
            return;
        }
        if (grantResults.length > 0) {
            List<String> deniedPermissionList = new ArrayList<String>();
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    deniedPermissionList.add(permissions[i]);
                }
            }
            if (deniedPermissionList.isEmpty()) {
                //已获取全部所需权限
                permissionAllGranted(mPermissionRequestCode);
            } else {

                //勾选了“禁止后不在询问”选项, 返回false
                for (String deniedPermission : deniedPermissionList) {
                    boolean flag = shouldShowRequestPermissionRationale(deniedPermission);
                    if (!flag) {
                        // 未获取到权限 并勾选了不再询问选项
                        permissionShouldShowRationale(deniedPermissionList, mPermissionRequestCode);
                        return;
                    }
                }
                // 未获取到所需全部权限
                permissionHasDenied(deniedPermissionList, mPermissionRequestCode);
            }
        }
    }

    /**
     * 获取应用详情页面intent（如果找不到要跳转的界面，也可以先把用户引导到系统设置页面）
     *
     * @return
     */
    public Intent getAppDetailSettingIntent() {
        Intent localIntent = new Intent();
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9) {
            localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            localIntent.setData(Uri.fromParts("package", getPackageName(), null));
        } else if (Build.VERSION.SDK_INT <= 8) {
            localIntent.setAction(Intent.ACTION_VIEW);
            localIntent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
            localIntent.putExtra("com.android.settings.ApplicationPkgName", getPackageName());
        }
        return localIntent;
    }

    /**
     * 已获取所需全部权限
     *
     * @param permissionRequestCode 获取权限请求码
     */
    private void permissionAllGranted(int permissionRequestCode) {
        if (listener != null) {
            listener.onGranted(permissionRequestCode);
        }
    }

    /**
     * 未获取到所需全部权限
     *
     * @param deniedList            未获取到的权限
     * @param permissionRequestCode 获取权限请求码
     */
    private void permissionHasDenied(List<String> deniedList, int permissionRequestCode) {
        if (listener != null) {
            listener.onDenied(deniedList, permissionRequestCode);
        }
    }

    /**
     * 未获取到相关权限并且勾选了不再询问
     *
     * @param deniedList            勾选了不在询问的权限
     * @param permissionRequestCode 获取权限请求码
     */
    private void permissionShouldShowRationale(List<String> deniedList, int permissionRequestCode) {
        if (listener != null) {
            listener.onShouldShowRationale(deniedList, permissionRequestCode);
        }
    }

    public interface PermissionListener {
        /**
         * 已获取到所需全部权限
         *
         * @param permissionRequestCode 请求码
         */
        void onGranted(int permissionRequestCode);

        /**
         * 未获取到所需全部权限
         *
         * @param deniedPermission      被拒绝的权限
         * @param permissionRequestCode 请求码
         */
        void onDenied(List<String> deniedPermission, int permissionRequestCode);

        /**
         * 未获取到所需全部权限并勾选不再提醒
         *
         * @param deniedPermission      勾选了不再询问的权限
         * @param permissionRequestCode 请求码
         */
        void onShouldShowRationale(List<String> deniedPermission, int permissionRequestCode);
    }
}